package com.zyc.app.woa;

import android.content.Context;
import android.content.Intent;
import com.zyc.app.woa.data.AccountInfo;
import com.zyc.app.woa.data.CachedArticle;
import com.zyc.app.woa.db.DBManager;
import com.zyc.app.woa.utils.*;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.ArrayList;

/**
 * Author: yingchang.zhang
 * Date  : 2014/11/28
 */
public class SubscribeAccounts {
    static ArrayList<AccountInfo> sSubscribes;

    public static void addAccount(AccountInfo accountInfo) {
        if (isExistInList(sSubscribes, accountInfo.wxId)) {
            WxUtils.toast(R.string.account_exist);
        } else {
            sSubscribes.add(accountInfo);
            DBManager.addAccount(accountInfo);
            WxUtils.toast(R.string.add_account_succeed);
        }
        StatisticUtil.addAccount(accountInfo);
    }

    public static void deleteAccount(final AccountInfo accountInfo) {
        sSubscribes.remove(accountInfo);
        AsyncTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                DBManager.removeCachedArticles(accountInfo.wxId);
                DBManager.removeAccount(accountInfo);
            }
        });
    }

    public static int getCount() {
        return sSubscribes.size();
    }

    public static AccountInfo getAccount(int position) {
        return position < getCount() ? sSubscribes.get(position) : null;
    }

    public static void init(Context context) {
        DBManager.init(context);
        sSubscribes = loadSubscriber();

        startCheckDataValid();
        if (CommonUtils.isWifiConnected()) {
            startUpdateArticles(context);
        }
    }

    public static ArrayList<AccountInfo> loadSubscriber() {
        return DBManager.getAccounts();
    }

    private static boolean isExistInList(ArrayList<AccountInfo> list, String wxId) {
        for (AccountInfo account : list) {
            if (account.wxId.equals(wxId)) {
                return true;
            }
        }
        return false;
    }

    public static void startUpdateArticles(Context context) {
        for (AccountInfo accountInfo : sSubscribes) {
            accountInfo.setTotalArticlesNum(WxConfig.DEFAULT_DOWNLOAD_SIZE);
            Intent intent = new Intent(context, DownloadService.class);
            intent.putExtra(WxConfig.ACCOUNT_INFO, accountInfo);
            context.startService(intent);
        }
    }

    public static void startCheckDataValid() {
        Trace.log("startCheckDataValid---" + sSubscribes.toString());
        //check local redundant data.
        checkLocalRedundantCaches();

        //TODO: check db redundant data.

        //delete readed articles
        startDeleteReadedArticles();
    }

    private static void checkLocalRedundantCaches() {
        AsyncTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                File cachePath = new File(WxConfig.ARTICLE_CACHE_PATH);
                String[] names = cachePath.list();
                if (null != names) {
                    for (String name : names) {
                        Trace.log("checkLocalRedundantCaches---name: " + name);
                        if (!isExistInList(sSubscribes, name)) {
                            //解决在打开文件时遭遇删除抛出的异常
                            File renameTo = new File(cachePath + Long.toString(System.currentTimeMillis()));
                            File deleteFile = new File(cachePath, name);
                            deleteFile.renameTo(renameTo);
                            FileUtils.deleteQuietly(renameTo);
                        }
                    }
                }
            }
        });

    }

    private static void startDeleteReadedArticles() {
        AsyncTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ArrayList<CachedArticle> list = DBManager.getReadedArticles();
                for (CachedArticle article : list) {
                    if (null != article && !article.isFavorite()) {
                        Trace.log("startDeleteReadedArticles--delete article: " + article.toString());
                        DBManager.deleteArticle(article);
                    }
                }
            }
        });
    }
}
